﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Text;
using System.Windows.Forms;
using JetBrains.Annotations;
using SF.Code.Extension.WinAPI;
using SG.Sys.Console.Cntrl;
using SG.Sys.Console.Process;
using SG.Sys.Console.View;

namespace SG.Sys.Console
{
    public class Program
    {
#pragma warning disable 0649
        private Guid _id;
        [UsedImplicitly] private Composer _composer;

        [ImportMany, UsedImplicitly]
        private IEnumerable<Lazy<IProcessWrapperFactory, IProcessWrapperFactoryData>> _processWrapperFactories;
#pragma warning restore 0649

        private Program()
        {
            _id = Guid.NewGuid();
            _composer = new Composer(this);
        }

        public IEnumerable<Lazy<IProcessWrapperFactory, IProcessWrapperFactoryData>> ProcessWrapperFactories { get { return _processWrapperFactories; } }

        private void Run()
        {
            var name = _id.ToString("D");
            System.Console.Title = name;
            // redirect console output to parent process;
            // must be before any calls to Console.WriteLine()
            Kernel32.AttachConsole(Kernel32.ATTACH_PARENT_PROCESS);

            System.Console.InputEncoding = new UTF8Encoding(false);

            var hWnd = User32.FindWindow(null, name); //put your console window caption here

            if (hWnd != IntPtr.Zero)
            {
                //Hide the window
                User32.ShowWindow(hWnd, 0); // 0 = SW_HIDE
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainConsole());    
        }

        public static Program Instance { get; private set; }
       
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Instance = new Program();
            Instance.Run();
        }
    }
}
